<template>
  <div class="app-container">
    <div class="filter-container query">
      <el-form :model="listQuery" label-position="right" label-width="100px">
        <el-row :gutter="10">
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="用户编号" prop="userCode">
              <el-input v-model="listQuery.userCode" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="用户姓名" prop="userName">
              <el-input v-model="listQuery.userName" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="用户归属机构" prop="orgCode">
              <OrgCascader v-model="listQuery.orgCode" :clearable="true" :show-all-levels="false" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="启用标记" prop="enableFlag">
              <el-select v-model="listQuery.enableFlag" clearable class="filter-item">
                <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="12">
            <el-button class="filter-item" type="primary" size="small" icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item" type="info" size="small" icon="el-icon-refresh" @click="handleReset">
              重置
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="success" size="small" icon="el-icon-circle-plus-outline" @click="handleCreate">
              新增
            </el-button>
            <el-button class="filter-item" type="danger" size="small" icon="el-icon-upload" @click="handleUpload">
              导入
            </el-button>
            <el-button :loading="downloadLoading" class="filter-item" type="warning" size="small" icon="el-icon-download" @click="handleDownload">
              导出
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-table
      :loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      size="small"
      @sort-change="sortChange"
    >
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
          <el-button size="mini" type="success" @click="handleRoles(row)">
            授权
          </el-button>
          <el-button size="mini" type="warning" @click="handleChangeUserPasswd(row)">
            密码
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="用户编号" prop="userCode" sortable="custom" width="150" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.userCode }}</span>
          <i v-if="scope.row.lockFlag === 'Y'" class="el-icon-lock" :title="'点击为用户' + scope.row.userCode + '解锁'" @click="handleUnlock(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="用户归属机构" prop="orgCode" sortable="custom" width="150" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.orgName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户姓名" prop="userName" sortable="custom" width="180" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用标记" prop="enableFlag" :formatter="formatter" sortable="custom" width="130" header-align="center" align="center" />
      <el-table-column label="联系电话" prop="userPhone" min-width="15%" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.userPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" prop="userEmail" min-width="20%" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.userEmail }}</span>
        </template>
      </el-table-column>
      <el-table-column label="NotesID" prop="notesid" min-width="10%" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.notesid }}</span>
        </template>
      </el-table-column>
      <el-table-column label="人力资源编号" prop="rphmid" min-width="12%" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.rphmid }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageNoSize" @pagination="getList" />

    <el-dialog title="用户授权角色" :visible.sync="dialogTransferVisible" top="3vh" width="850px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <div style="text-align: center">
        <el-transfer v-model="selectedRoles" style="text-align: left; display: inline-block" :data="unselectRoles" :titles="['可选角色', '授权角色']" filterable />
      </div>
      <div slot="footer">
        <el-button @click="dialogTransferVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitUserRoleAuth">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" top="3vh" width="520px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" class="form-center">
        <el-form-item label="用户编号" prop="userCode">
          <el-input v-model="temp.userCode" maxlength="64" :disabled="dialogStatus==='update'" />
        </el-form-item>
        <el-form-item label="用户归属机构" prop="orgCode">
          <OrgCascader ref="OrgCascader" v-model="temp.orgCode" :clearable="true" :show-all-levels="true" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="temp.userName" maxlength="128" />
        </el-form-item>
        <el-form-item label="启用标记" prop="enableFlag">
          <el-select v-model="temp.enableFlag" placeholder="启用标记" clearable>
            <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="userPhone">
          <el-input v-model="temp.userPhone" maxlength="32" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="temp.userEmail" maxlength="128" />
        </el-form-item>
        <el-form-item label="NotesID" prop="notesid">
          <el-input v-model="temp.notesid" maxlength="16" />
        </el-form-item>
        <el-form-item label="人力资源编号" prop="rphmid">
          <el-input v-model="temp.rphmid" maxlength="16" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="Excel导入用户信息" :visible.sync="uploadExcelDialogVisible" center>
      <div class="app-container">
        <el-upload
          ref="upload"
          action="customized"
          :limit="1"
          accept=".xls,.xlsx"
          :http-request="handleExcelUpload"
          :auto-upload="false"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button :loading="fileUploading" style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
          <el-button style="margin-left: 10px;" size="small" type="info" @click="handleDownloadTemplate">下载模板</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
        </el-upload>
      </div>
    </el-dialog>

    <el-dialog
      title="用户密码修改"
      :visible.sync="dialogPasswdFormVisible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
      :destroy-on-close="true"
      width="500px"
    >
      <el-form
        ref="dataPasswdForm"
        :rules="rules"
        :model="tempPasswd"
        label-position="right"
        label-width="150px"
        class="form-center"
      >
        <el-form-item prop="newpasswd" class="form-item-center">
          <el-radio v-model="tempPasswd.passType" label="1">手动输入</el-radio>
          <el-radio v-model="tempPasswd.passType" label="2">随机密码</el-radio>
          <el-radio v-model="tempPasswd.passType" label="3">默认密码</el-radio>
        </el-form-item>
        <el-form-item label="新的密码" prop="newpasswd">
          <el-input v-if="tempPasswd.passType === '1'" v-model="tempPasswd.newpasswd" minlength="8" maxlength="64" placeholder="新用户密码" show-password />
          <span v-if="tempPasswd.passType !== '1'" style="color:red;">{{ tempPasswd.newpasswd }}</span>
        </el-form-item>
        <el-form-item v-if="tempPasswd.passType === '1'" label="验证密码" prop="repasswd">
          <el-input v-model="tempPasswd.repasswd" minlength="8" maxlength="64" placeholder="确认用户密码" show-password />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPasswdFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="formSubmiting" @click="changeUserPasswd">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, createAuthUser, updateAuthUser, deleteAuthUser, unlockUser, updateUserRoleAuth, getUserRoles, changePasswd, importAuthUser, exportAuthUser, exportAuthUserTemplate } from '@/api/base/auth/authUser'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { saveRespExcel } from '@/utils'
import { setOptionData, valueFormate } from '@/utils/dict'
import OrgCascader from '@/components/Org/cascader'
import { getCaptchaw150h40 } from '@/api/base/common'
import { encryptSM2 } from '@/utils/sm-crypto.js'

export default {
  name: 'AuthUser',
  components: { Pagination, OrgCascader },
  data() {
    const validateNewpasswd = (rule, value, callback) => {
      if (value == null || value.length > 64 || value.length < 1) {
        callback(new Error('密码应为长度为8至64个字符的满足总行要求的数字、字母、特殊字符组合'))
      }
      var reg = new RegExp(/^(?![^a-zA-Z]+$)(?!\D+$)/)
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('密码应为长度为8至64个字符的满足总行要求的数字、字母、特殊字符组合'))
      }
    }
    const validateRepasswd = (rule, value, callback) => {
      if (value == null || value.length > 64 || value.length < 1) {
        callback(new Error('密码应为长度为8至64个字符的满足总行要求的数字、字母、特殊字符组合'))
      }
      if (value === this.tempPasswd.newpasswd) {
        callback()
      } else {
        callback(new Error('两次输入密码不一致'))
      }
    }
    return {
      list: null,
      unselectRoles: [],
      selectedRoles: [],
      dialogTransferVisible: false,
      uploadExcelDialogVisible: false,
      dialogPasswdFormVisible: false,
      selectedUserId: null,
      userTypeOptions: [],
      enableFlagOptions: [],
      total: 0,
      listLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        sortField: undefined,
        sortOrder: undefined,
        userCode: '',
        userName: '',
        userType: '',
        orgCode: '',
        enableFlag: ''
      },
      temp: {
        id: null,
        userType: '',
        userCode: '',
        userName: '',
        userPhone: '',
        userEmail: '',
        orgCode: '',
        commonUserCode: '',
        commonOrgCode: '',
        userAvatar: '',
        enableFlag: 'Y',
        createAt: undefined,
        createBy: '',
        updateAt: undefined,
        updateBy: ''
      },
      tempPasswd: {
        passType: '1',
        userCode: '',
        newpasswd: '',
        repasswd: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新用户信息',
        create: '创建用户信息'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        userType: [{ required: true, message: '用户类型不能为空', trigger: 'change' }],
        userCode: [{ required: true, message: '用户编号不能为空', trigger: 'change' }],
        userName: [{ required: true, message: '用户姓名不能为空', trigger: 'change' }],
        userPhone: [{ max: 32, message: '用户手机最大长度为32个字符', trigger: 'change' }],
        userEmail: [{ max: 128, message: '用户邮箱最大长度不能超过128个字符', trigger: 'change' }],
        orgCode: [{ required: true, message: '用户归属机构不能为空', trigger: 'change' }],
        enableFlag: [{ required: true, message: '启用标记不能为空', trigger: 'change' }],
        newpasswd: [{ required: true, message: '新的密码不能为空', trigger: 'change' },
          { min: 8, max: 64, message: '密码应为长度为8至64个字符的满足总行要求的数字、字母、特殊字符组合', trigger: 'change' },
          { validator: validateNewpasswd, message: '密码应为长度为8至64个字符的满足总行要求的数字、字母、特殊字符组合', trigger: 'change' }],
        repasswd: [{ required: true, message: '请验证新的密码', trigger: 'change' },
          { min: 8, max: 64, message: '两次输入密码不一致', trigger: 'change' },
          { validator: validateRepasswd, message: '两次输入密码不一致', trigger: 'change' }]
      },
      downloadLoading: false,
      fileUploading: false,
      formSubmiting: false,
      captcha: {
        captchHash: '',
        publicKey: '',
        captchaId: ''
      }
    }
  },
  watch: {
    'tempPasswd.passType': function(val, oldVal) {
      if (val === '1') {
        this.tempPasswd.newpasswd = ''
        this.tempPasswd.repasswd = ''
      } else if (val === '2') {
        // 生成随机密码
        const passAlpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
        const passNumber = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        const passDot = ['&', '!', '*', '#', '@', '(', ')', '=']
        const passwdLen = 8
        let password = ''
        for (var i = 0; i < passwdLen; i++) {
          if (i % 3 === 0) {
            const x = Math.floor(Math.random() * passAlpha.length)
            password += passAlpha[x]
          } else if (i % 3 === 1) {
            const x = Math.floor(Math.random() * passDot.length)
            password += passDot[x]
          } else {
            const x = Math.floor(Math.random() * passNumber.length)
            password += passNumber[x]
          }
        }
        this.tempPasswd.newpasswd = password
        this.tempPasswd.repasswd = password
      } else {
        const password = 'CXM_4$1%3P'
        this.tempPasswd.newpasswd = password
        this.tempPasswd.repasswd = password
      }
      this.$nextTick(() => {
        this.$refs['dataPasswdForm'].clearValidate()
      })
    }
  },
  created() {
    this.initDictInfos()
    this.getList()
  },
  methods: {
    genCaptcha() {
      getCaptchaw150h40().then(
        (response) => {
          this.captcha.captchHash = response.data.hashCode
          this.captcha.publicKey = response.data.publicKey
          this.captcha.captchaId = response.data.captchaId
        }
      )
    },
    initDictInfos() { // 初始化数据字典
      // 加载下拉数据
      const optionsMap = new Map()
      optionsMap.set('BASE_USER_TYPE', this.userTypeOptions)
      optionsMap.set('ENABLE_FLAG', this.enableFlagOptions)
      setOptionData(optionsMap)
    },
    formatter(row, column, cellValue, index) {
      return valueFormate(this, column.property, cellValue)
    },
    getList() {
      this.listLoading = true
      getUserList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        pageNo: 1,
        pageSize: 20,
        sortField: undefined,
        sortOrder: undefined,
        userCode: '',
        userName: '',
        userType: '',
        orgCode: '',
        enableFlag: ''
      }
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: 'Success',
        type: 'success'
      })
    },
    resetTemp() {
      this.temp = {
        userCode: '',
        userName: '',
        userPhone: '',
        orgCode: '',
        userType: '',
        enableFlag: 'Y'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createAuthUser(this.temp).then(response => {
            this.dialogFormVisible = false
            this.getList()
            this.$message({
              message: '用户信息保存成功!',
              type: 'success'
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$msgbox({
        type: 'warning',
        title: '确认',
        message: '确认删除用户[' + row.userCode + ']?',
        showCancelButton: true,
        showClose: false,
        closeOnPressEscape: false,
        closeOnClickModal: false,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            deleteAuthUser(row.id).then((response) => {
              this.getList()
              this.$message({
                message: '用户[' + row.userCode + ']删除成功!',
                type: 'success'
              })
              done()
              instance.confirmButtonLoading = false
            }, (response) => {
              done()
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      })
    },
    sortChange(data) {
      const { prop, order } = data
      this.sortByField(prop, order)
    },
    sortByField(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'asc'
      } else if (order === 'descending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'desc'
      } else {
        this.listQuery.sortField = undefined
        this.listQuery.sortOrder = undefined
      }
      this.handleFilter()
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateAuthUser(this.temp).then(response => {
            this.getList()
            this.dialogFormVisible = false
            this.$message({
              message: '用户信息更新成功!',
              type: 'success'
            })
          })
        }
      })
    },
    handleRoles(row) {
      this.unselectRoles = []
      this.selectedRoles = []
      this.selectedUserId = row.id
      getUserRoles(row.id).then(response => {
        for (const v of response.data.allValidRoles) {
          this.unselectRoles.push({
            key: v.id,
            label: v.roleName,
            disabled: false
          })
        }
        for (const userRole of response.data.userRoles) {
          if (userRole && userRole.roleId) {
            this.selectedRoles.push(userRole.roleId)
          }
        }
      })
      this.dialogTransferVisible = true
    },
    submitUserRoleAuth() {
      updateUserRoleAuth(this.selectedUserId, JSON.stringify(this.selectedRoles)).then(response => {
        this.dialogTransferVisible = false
        this.selectedUserId = null
        this.unselectRoles = []
        this.selectedRoles = []
      })
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleUpload() {
      this.uploadExcelDialogVisible = true
    },
    handleExcelUpload(file) {
      if (!file || !file.file) {
        return function() {
          Promise.resolve(file)
        }
      }
      this.fileUploading = true
      importAuthUser(file).then(response => {
        this.getList()
        this.$message({
          message: '批量导入用户信息成功!',
          type: 'success'
        })
        this.uploadExcelDialogVisible = false
        this.fileUploading = false
      }, response => {
        this.fileUploading = false
      })
    },
    handleDownload() {
      this.downloadLoading = true
      exportAuthUser(this.listQuery).then(response => {
        saveRespExcel(response)
        this.downloadLoading = false
      }, response => {
        this.downloadLoading = false
      })
    },
    handleDownloadTemplate() {
      this.downloadLoading = true
      exportAuthUserTemplate().then(response => {
        saveRespExcel(response)
        this.downloadLoading = false
      }, response => {
        this.downloadLoading = false
      })
    },
    handleUnlock(row) {
      this.$msgbox({
        type: 'warning',
        title: '确认',
        message: '确认解锁用户[' + row.userCode + ']?',
        showCancelButton: true,
        showClose: false,
        closeOnPressEscape: false,
        closeOnClickModal: false,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            unlockUser(row.userCode).then((response) => {
              this.getList()
              this.$message({
                message: '用户[' + row.userCode + ']解锁成功!',
                type: 'success'
              })
              done()
              instance.confirmButtonLoading = false
            }, (response) => {
              done()
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      })
    },
    handleChangeUserPasswd(row) {
      this.tempPasswd = {
        passType: '1',
        userCode: row.userCode,
        newpasswd: '',
        repasswd: ''
      }
      this.$nextTick(() => {
        this.$refs['dataPasswdForm'].clearValidate()
      })

      this.genCaptcha()
      this.dialogPasswdFormVisible = true
    },
    changeUserPasswd() {
      this.$refs['dataPasswdForm'].validate((valid) => {
        if (valid) {
          const data = {
            userCode: this.tempPasswd.userCode,
            newPasswd: encryptSM2(this.tempPasswd.newpasswd, this.captcha.publicKey),
            captchaId: this.captcha.captchaId
          }
          this.formSubmiting = true
          changePasswd(data).then(() => {
            this.formSubmiting = false
            this.dialogPasswdFormVisible = false
            this.$message({
              message: '用户密码修改成功!',
              type: 'success'
            })
          }, () => {
            this.genCaptcha()
            this.formSubmiting = false
          })
        }
      })
    }
  }
}
</script>
